package org.unidata.mdm.rest.v1.data.service.atomic;

import java.util.Collections;
import java.util.Objects;

import org.unidata.mdm.data.context.GetRequestContext.GetRequestContextBuilder;
import org.unidata.mdm.rest.system.service.TypedRestInputRenderer;
import org.unidata.mdm.rest.v1.data.module.DataRestModule;
import org.unidata.mdm.rest.v1.data.ro.atomic.AtomicDataGetRequestRO;
import org.unidata.mdm.rest.v1.data.ro.records.GetRecordRequestRO;
import org.unidata.mdm.system.context.InputCollector;
import org.unidata.mdm.system.type.rendering.FieldDef;
import org.unidata.mdm.system.type.rendering.FragmentDef;
import org.unidata.mdm.system.type.rendering.MapInputSource;
import org.unidata.mdm.system.util.ConvertUtils;

/**
 * Atomic upsert request renderer
 *
 * @author Alexandr Serov
 * @since 09.11.2020
 **/
public class AtomicDataGetRequestRenderer extends TypedRestInputRenderer<AtomicDataGetRequestRO> {

    public AtomicDataGetRequestRenderer() {
        super(AtomicDataGetRequestRO.class, Collections.singletonList(FieldDef.fieldDef(DataRestModule.MODULE_ID, GetRecordRequestRO.class)));
    }

    @Override
    protected void renderFields(FragmentDef fragmentDef, InputCollector collector, AtomicDataGetRequestRO source, MapInputSource fieldValues) {

        GetRecordRequestRO request = fieldValues.get(DataRestModule.MODULE_ID, GetRecordRequestRO.class);
        if (request != null && (collector instanceof GetRequestContextBuilder)) {

            GetRequestContextBuilder ctxb = (GetRequestContextBuilder) collector;
            ctxb
                .etalonKey(request.getEtalonId())
                .entityName(request.getEntityName())
                .externalId(Objects.nonNull(request.getExternalId()) ? request.getExternalId().getExternalId() : null)
                .sourceSystem(Objects.nonNull(request.getExternalId()) ? request.getExternalId().getSourceSystem() : null)
                .lsn(Objects.nonNull(request.getLsn()) ? request.getLsn().getLsn() : null)
                .shard(Objects.nonNull(request.getLsn()) ? request.getLsn().getShard() : null)
                .forOperationId(request.getOperationId())
                .includeInactive(request.isIncludeInactive())
                .draftId(request.getDraftId())
                .diffToDraft(request.isDiffToDraft())
                .diffToPrevious(request.isDiffToPrevious())
                .forDate(ConvertUtils.localDateTime2Date(request.getTimelineDate()));
        }
    }
}
